<template>
  <div class="system-settings">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="header-title">系统设置</span>
          <el-button type="primary" :icon="Plus" @click="handleAddSetting">添加设置项</el-button>
        </div>
      </template>

      <!-- 设置分类标签 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="系统功能" name="functions">
          <div class="settings-content">
            <el-card 
              v-for="setting in functionSettings" 
              :key="setting.id"
              class="setting-card"
              shadow="hover"
            >
              <template #header>
                <div class="setting-header">
                  <div class="setting-info">
                    <h3 class="setting-title">{{ setting.settingKey }}</h3>
                    <p class="setting-desc">{{ setting.description || '暂无描述' }}</p>
                  </div>
                  <el-switch
                    v-model="setting.status"
                    :active-value="1"
                    :inactive-value="0"
                    active-text="启用"
                    inactive-text="禁用"
                    @change="handleStatusChange(setting)"
                  />
                </div>
              </template>
              <div class="setting-body">
                <el-input
                  v-model="setting.settingValue"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入设置值"
                  @blur="handleValueChange(setting)"
                />
                <div class="setting-actions">
                  <el-button 
                    type="primary" 
                    size="small" 
                    :icon="Edit"
                    @click="editSetting(setting)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    :icon="Delete"
                    @click="deleteSetting(setting.id)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="系统参数" name="parameters">
          <div class="settings-content">
            <el-card 
              v-for="setting in parameterSettings" 
              :key="setting.id"
              class="setting-card"
              shadow="hover"
            >
              <template #header>
                <div class="setting-header">
                  <div class="setting-info">
                    <h3 class="setting-title">{{ setting.settingKey }}</h3>
                    <p class="setting-desc">{{ setting.description || '暂无描述' }}</p>
                  </div>
                </div>
              </template>
              <div class="setting-body">
                <el-input
                  v-model="setting.settingValue"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入参数值"
                  @blur="handleValueChange(setting)"
                />
                <div class="setting-actions">
                  <el-button 
                    type="primary" 
                    size="small" 
                    :icon="Edit"
                    @click="editSetting(setting)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    :icon="Delete"
                    @click="deleteSetting(setting.id)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="所有设置" name="all">
          <div class="settings-table">
            <el-table 
              :data="settings" 
              v-loading="loading"
              stripe
              border
              style="width: 100%"
            >
              <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
              <el-table-column label="键名" prop="settingKey" min-width="150"></el-table-column>
              <el-table-column label="值" prop="settingValue" min-width="200" show-overflow-tooltip></el-table-column>
              <el-table-column label="描述" prop="description" min-width="200" show-overflow-tooltip></el-table-column>
              <el-table-column label="类型" prop="type" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.type === 'function' ? 'success' : 'info'">
                    {{ row.type === 'function' ? '功能' : '参数' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="status" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.status === 1 ? 'success' : 'info'">
                    {{ row.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button 
                    type="primary" 
                    size="small" 
                    :icon="Edit"
                    @click="editSetting(row)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    :icon="Delete"
                    @click="deleteSetting(row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加/编辑对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        @close="handleDialogClose"
      >
        <el-form 
          :model="formData" 
          :rules="formRules" 
          ref="formRef"
          label-width="100px"
        >
          <el-form-item label="键名" prop="settingKey">
            <el-input 
              v-model="formData.settingKey" 
              placeholder="请输入键名，如：email_notification, max_upload_size"
              :disabled="isEdit"
            ></el-input>
            <div class="form-tip">建议使用下划线命名，如：email_notification</div>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-radio-group v-model="formData.type">
              <el-radio label="function">系统功能</el-radio>
              <el-radio label="parameter">系统参数</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="值" prop="settingValue">
            <el-input 
              v-model="formData.settingValue" 
              type="textarea"
              :rows="4"
              placeholder="请输入设置值"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input 
              v-model="formData.description" 
              type="textarea"
              :rows="2"
              placeholder="请输入描述信息"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status" v-if="formData.type === 'function'">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="saving">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';

export default {
  name: 'SystemSettings',
  components: {
    Plus,
    Edit,
    Delete
  },
  data() {
    return {
      settings: [],
      loading: false,
      activeTab: 'functions',
      dialogVisible: false,
      dialogTitle: '添加设置项',
      isEdit: false,
      saving: false,
      formData: {
        id: null,
        settingKey: '',
        settingValue: '',
        description: '',
        type: 'function',
        status: 1
      },
      formRules: {
        settingKey: [
          { required: true, message: '请输入键名', trigger: 'blur' },
          { pattern: /^[a-z_][a-z0-9_]*$/, message: '键名只能包含小写字母、数字和下划线，且不能以数字开头', trigger: 'blur' }
        ],
        settingValue: [
          { required: true, message: '请输入值', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      }
    };
  },
  computed: {
    functionSettings() {
      return this.settings.filter(item => item.type === 'function');
    },
    parameterSettings() {
      return this.settings.filter(item => item.type === 'parameter');
    }
  },
  mounted() {
    this.fetchSettings();
  },
  methods: {
    async fetchSettings() {
      this.loading = true;
      try {
        const res = await axios.get('http://localhost:8080/api/admin/system-setting/list');
        if (res.data.code === 200) {
          this.settings = res.data.data || [];
        } else {
          ElMessage.error(res.data.msg || '获取设置列表失败');
        }
      } catch (error) {
        console.error('获取设置列表失败:', error);
        ElMessage.error('获取设置列表失败：' + (error.message || '网络错误'));
      } finally {
        this.loading = false;
      }
    },
    handleTabChange(tab) {
      // 切换标签时不需要特殊处理
    },
    handleAddSetting() {
      this.dialogTitle = '添加设置项';
      this.isEdit = false;
      this.formData = {
        id: null,
        settingKey: '',
        settingValue: '',
        description: '',
        type: 'function',
        status: 1
      };
      this.dialogVisible = true;
    },
    editSetting(setting) {
      this.dialogTitle = '编辑设置项';
      this.isEdit = true;
      this.formData = {
        id: setting.id,
        settingKey: setting.settingKey,
        settingValue: setting.settingValue,
        description: setting.description || '',
        type: setting.type || 'function',
        status: setting.status === '启用' || setting.status === 1 ? 1 : 0
      };
      this.dialogVisible = true;
    },
    async handleStatusChange(setting) {
      try {
        const res = await axios.put('http://localhost:8080/api/admin/system-setting/update', {
          id: setting.id,
          settingKey: setting.settingKey,
          settingValue: setting.settingValue,
          description: setting.description,
          type: setting.type,
          status: setting.status
        });
        if (res.data.code === 200) {
          ElMessage.success('状态更新成功');
        } else {
          ElMessage.error(res.data.msg || '状态更新失败');
          // 恢复原状态
          setting.status = setting.status === 1 ? 0 : 1;
        }
      } catch (error) {
        console.error('更新状态失败:', error);
        ElMessage.error('更新状态失败：' + (error.message || '网络错误'));
        // 恢复原状态
        setting.status = setting.status === 1 ? 0 : 1;
      }
    },
    async handleValueChange(setting) {
      try {
        const res = await axios.put('http://localhost:8080/api/admin/system-setting/update', {
          id: setting.id,
          settingKey: setting.settingKey,
          settingValue: setting.settingValue,
          description: setting.description,
          type: setting.type,
          status: setting.status
        });
        if (res.data.code === 200) {
          ElMessage.success('设置值已更新');
        } else {
          ElMessage.error(res.data.msg || '更新失败');
        }
      } catch (error) {
        console.error('更新设置值失败:', error);
        ElMessage.error('更新失败：' + (error.message || '网络错误'));
      }
    },
    async deleteSetting(id) {
      try {
        await ElMessageBox.confirm('确定要删除这条设置吗？', '提示', {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        });

        const res = await axios.delete(`http://localhost:8080/api/admin/system-setting/delete/${id}`);
        if (res.data.code === 200) {
          ElMessage.success('删除成功');
          this.fetchSettings();
        } else {
          ElMessage.error(res.data.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除设置失败:', error);
          ElMessage.error('删除失败：' + (error.message || '网络错误'));
        }
      }
    },
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) {
          return;
        }

        this.saving = true;
        try {
          let res;
          if (this.isEdit) {
            // 编辑
            res = await axios.put('http://localhost:8080/api/admin/system-setting/update', this.formData);
          } else {
            // 添加
            res = await axios.post('http://localhost:8080/api/admin/system-setting/add', this.formData);
          }

          if (res.data.code === 200) {
            ElMessage.success(this.isEdit ? '更新成功' : '添加成功');
            this.dialogVisible = false;
            this.fetchSettings();
          } else {
            ElMessage.error(res.data.msg || (this.isEdit ? '更新失败' : '添加失败'));
          }
        } catch (error) {
          console.error('保存设置失败:', error);
          ElMessage.error('保存失败：' + (error.message || '网络错误'));
        } finally {
          this.saving = false;
        }
      });
    },
    handleDialogClose() {
      this.$refs.formRef?.resetFields();
    }
  }
};
</script>

<style scoped>
.system-settings {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.settings-content {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.setting-card {
  margin-bottom: 0;
}

.setting-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.setting-info {
  flex: 1;
}

.setting-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.setting-desc {
  font-size: 14px;
  color: #909399;
  margin: 0;
  line-height: 1.5;
}

.setting-body {
  padding-top: 10px;
}

.setting-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.settings-table {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

@media (max-width: 768px) {
  .settings-content {
    grid-template-columns: 1fr;
  }

  .setting-header {
    flex-direction: column;
    gap: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
